/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.incad.psh.pshassign.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import org.apache.commons.io.IOUtils;

/**
 *
 * @author alberto
 */
public class PSHNames {

    public String getNames(String path) throws Exception {
        String q = "";
        String[] ids = path.substring(1).split("/");
        for (int i = 0; i < ids.length; i++) {
            String id = ids[i];
            if (i > 0) {
                q += "+OR+";
            }
            q += "id:" + id;
        }
        String urlParameters = "rows=1000&wt=json&fl=id,csPrefLabel&q=" + q;
        StringWriter res = new StringWriter();
        postData(new StringReader(urlParameters), res);
        return res.toString();
//        String urlStr = "http://localhost:8983/solr/PSH/select?rows=1000&wt=json&fl=id,csPrefLabel&q=" + q;
//        java.net.URL url = new java.net.URL(urlStr);
//        InputStream is = url.openStream();
//        StringWriter writer = new StringWriter();
//        IOUtils.copy(is, writer, "UTF-8");
//        return writer.toString();

    }
    
    private void postData(Reader data, StringWriter output)
            throws Exception {
        String request = Options.getOption("psh", "solr") + "/select";
        java.net.URL url = new java.net.URL(request); 
        HttpURLConnection urlc = null;
        String POST_ENCODING = "UTF-8";
        try {
            urlc = (HttpURLConnection) url.openConnection();
            try {
                urlc.setRequestMethod("POST");
            } catch (ProtocolException e) {
                throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
            }
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            urlc.setRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=" + POST_ENCODING);

            OutputStream out = urlc.getOutputStream();

            try {
                Writer writer = new OutputStreamWriter(out, POST_ENCODING);
                pipe(data, writer);
                writer.close();
            } catch (IOException e) {
                throw new Exception("IOException while posting data", e);
            } finally {
                if (out != null) {
                    out.close();
                }
            }

            InputStream in = urlc.getInputStream();
            int status = urlc.getResponseCode();
            StringBuilder errorStream = new StringBuilder();
            try {
                if (status != HttpURLConnection.HTTP_OK) {
                    errorStream.append("postData URL=").append(request).append(" HTTP response code=").append(status).append(" ");
                    throw new Exception("URL=" + request + " HTTP response code=" + status);
                }
                
                
                
                IOUtils.copy(in, output, "UTF-8");
                
//                Reader reader = new InputStreamReader(in);
//                pipeString(reader, output);
//                reader.close();
            } catch (IOException e) {
                throw new Exception("IOException while reading response", e);
            } finally {
                if (in != null) {
                    in.close();
                }
            }

            InputStream es = urlc.getErrorStream();
            if (es != null) {
                try {
                    Reader reader = new InputStreamReader(es);
                    pipeString(reader, errorStream);
                    reader.close();
                } catch (IOException e) {
                    throw new Exception("IOException while reading response", e);
                } finally {
                    if (es != null) {
                        es.close();
                    }
                }
            }
            if (errorStream.length() > 0) {
                throw new Exception("postData error: " + errorStream.toString());
            }

        } catch (IOException e) {
            throw new Exception("Solr has throw an error. Check tomcat log. " + e);
        } finally {
            if (urlc != null) {
                urlc.disconnect();
            }
        }
    }
    
    /**
     * Pipes everything from the reader to the writer via a buffer
     */
    private void pipe(Reader reader, Writer writer) throws IOException {
        char[] buf = new char[1024];
        int read = 0;
        while ((read = reader.read(buf)) >= 0) {
            writer.write(buf, 0, read);
        }
        writer.flush();
    }

    /**
     * Pipes everything from the reader to the writer via a buffer except lines
     * starting with '<?'
     */
    private void pipeString(Reader reader, StringBuilder writer) throws IOException {
        char[] buf = new char[102400];
        int read = 0;
        while ((read = reader.read(buf)) >= 0) {
            if (!(buf[0] == '<' && buf[1] == '?')) {
                writer.append(buf, 0, read);
            }
        }
    }
}
